package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.EmpExprMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Emp;
import com.itheima.pojo.EmpExpr;
import com.itheima.pojo.EmpQueryParam;
import com.itheima.pojo.PageResult;
import com.itheima.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.function.Consumer;

@Slf4j
@Service
public class EmpServiceImpl implements EmpService {
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private EmpExprMapper empExprMapper;

    @Override
    public PageResult findAll(EmpQueryParam e) {
        //设置分页参数
        PageHelper.startPage(e.getPage(), e.getPageSize());
        //执行查询
        List<Emp> rows = empMapper.findAll(e);
        Page<Emp> p = (Page<Emp>) rows;

        //封装结果
        return new PageResult(p.getTotal(), p.getResult());
    }

    @Transactional
    @Override
    public void save(Emp emp) {
        //保存员工基本信息
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        log.info("保存员工基本信息：{}", emp);
        empMapper.insert(emp);
        //获取员工id
        Integer empId = emp.getId();
        log.info("获取员工id：{}", empId);

        //保存员工工作经历
        List<EmpExpr> exprList = emp.getExprList();
        if(!CollectionUtils.isEmpty(exprList)){
            exprList.forEach((EmpExpr empExpr) -> {
                    empExpr.setEmpId(empId);
                    empExprMapper.insert(empExpr);
                });

        }



    }

    @Override
    @Transactional
    public void deleteById(Integer[] ids) {
        for(Integer id : ids){
            empMapper.deleteById(id);
            empExprMapper.deleteByEmpId(id);
        }
    }

    @Override
    public Emp findById(Integer id) {
        Emp e = empMapper.findById(id);
        e.setExprList(empExprMapper.findByEmpId(id));
        return e;
    }

    @Transactional
    @Override
    public void update(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.update(emp);
        empExprMapper.deleteByEmpId(emp.getId());
        for(EmpExpr empExpr : emp.getExprList()){
            empExpr.setEmpId(emp.getId());
            empExprMapper.insert(empExpr);
        }

    }

    @Override
    public List<Emp> list() {
        return empMapper.list();
    }
}
